package dynamic.ibatis.scripting.defaults;

import dynamic.ibatis.builder.DSqlSourceBuilder;
import dynamic.ibatis.mapping.DBoundSql;
import dynamic.ibatis.mapping.DSqlSource;
import dynamic.ibatis.scripting.xmltags.DynamicContext;
import dynamic.ibatis.scripting.xmltags.SqlNode;
import dynamic.ibatis.session.DConfiguration;

import java.util.HashMap;



public class DRawSqlSource implements DSqlSource {

    private final DSqlSource sqlSource;

    public DRawSqlSource(DConfiguration configuration, SqlNode rootSqlNode, Class<?> parameterType) {
        this(configuration, getSql(configuration, rootSqlNode), parameterType);
    }

    public DRawSqlSource(DConfiguration configuration, String sql, Class<?> parameterType) {
        DSqlSourceBuilder sqlSourceParser = new DSqlSourceBuilder(configuration);
        Class<?> clazz = parameterType == null ? Object.class : parameterType;
        sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
    }

    private static String getSql(DConfiguration configuration, SqlNode rootSqlNode) {
        DynamicContext context = new DynamicContext(configuration, null);
        rootSqlNode.apply(context);
        return context.getSql();
    }

    @Override
    public DBoundSql getBoundSql(Object parameterObject) {
        return sqlSource.getBoundSql(parameterObject);
    }

}
